package cn.xmoit.config;

import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * 1、EnableGlobalMethodSecurity(prePostEnabled = true)：开启对 Spring Security 注解的方法，进行权限验证。
 * 2、EnableOAuth2Sso：开启 Sso 功能
 *
 * @author fangyy
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableOAuth2Sso
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()

			// api接口需要admin管理员才能访问
			.antMatchers("/api/**")
			.hasRole("ADMIN")

			// 其余所有请求全部需要鉴权认证
			.anyRequest()
			.authenticated()

			// 关闭跨域保护;
			.and()
			.csrf()
			.disable();
	}

	@Bean
	RoleHierarchy roleHierarchy() {
		RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
		hierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER");
		return hierarchy;
	}

}
